package checkStatus;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import slaverDown.SlaverDown;

import dataStruct.SlaverStatus;


public class CheckSlaverStatus extends Thread{
	public CheckSlaverStatus(final Map<Integer, SlaverStatus> slaverMap, SlaverDown slaverDown)
	{
			CheckSlaverStatus.slaverMap = slaverMap;
			CheckSlaverStatus.slaverDown  = slaverDown;
			  Properties intervalProper = new Properties();   
			  try {   
				  intervalProper.load(new FileInputStream("conf/config.ini"));
			  } catch (IOException e1) {   
			   e1.printStackTrace();   
			  }   
			  offlineInterVal = Long.parseLong(intervalProper.getProperty("offlineInterval"));
			  shutdownInterval = Long.parseLong(intervalProper.getProperty("shutdownInterval"));
	}
	

	public void run()
	{	
		while(true)
		{
			try {
				checkOnce();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private void checkOnce() throws SQLException
	{
		for(Entry<Integer, SlaverStatus> entry: slaverMap.entrySet())
		{
			Integer key = entry.getKey();
			long lastBeatTime = entry.getValue().lastBeatTime;
			if(!entry.getValue().offline && (System.currentTimeMillis() - lastBeatTime > offlineInterVal))
			{
				slaverMap.put(key,new SlaverStatus(true, lastBeatTime));
					System.out.println("slaver[" + key + "] has offline");
					slaverMap.remove(key);
			}
			else if(System.currentTimeMillis() - lastBeatTime > shutdownInterval)
			{
				System.out.println("slaver[" + key + "] has shutdown");
				slaverMap.remove(key);
				// chunk move
				slaverDown.move_chunk(key);
			}
		}
	}
	
	private static Map<Integer, SlaverStatus> slaverMap;
	private static long offlineInterVal;
	private static long shutdownInterval;
	private static SlaverDown slaverDown;
}
